package com.ymatou.shop.ui.activity;

import java.util.ArrayList;

import android.app.LocalActivityManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;

import com.ymatou.shop.R;

public abstract class BaseTabActivity extends BaseActivity implements
		TabHost.OnTabChangeListener {
	
private static final String STATES_KEY = "android:states";
	
	private TabHost mTabHost;
	private TabWidget mTabWidget;
	
	private LocalActivityManager mLocalActivityManager;
	protected ArrayList<View> mTabViews;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		mLocalActivityManager = new LocalActivityManager(this, true);
		Bundle states = savedInstanceState != null
                ? (Bundle) savedInstanceState.getBundle(STATES_KEY) : null;
		mLocalActivityManager.dispatchCreate(states);
		
		mTabViews = new ArrayList<View>();
	}
	
	@Override
	protected void setupViews() {
		super.setupViews();
		
		mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		mTabWidget = (TabWidget) findViewById(android.R.id.tabs);
		mTabHost.setup(mLocalActivityManager);
		
		mTabHost.setOnTabChangedListener(this);
	}
	
	@Override
    public void onResume() {
        super.onResume();
        mLocalActivityManager.dispatchResume();
    }
	
	@Override
	public void onPause() {
        super.onPause();
        mLocalActivityManager.dispatchPause(isFinishing());
    }

    @Override
    public void onStop() {
        super.onStop();
        mLocalActivityManager.dispatchStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mLocalActivityManager.dispatchDestroy(isFinishing());
    }
	
	protected TabHost getTabHost() {
		return mTabHost;
	}
	
	protected TabWidget getTabWidget() {
		return mTabWidget;
	}

	protected void addTab(String tagId, String text, Intent intent) {
		View view = getLayoutInflater().inflate(R.layout.tabbar_indicator, mTabWidget, false);
		view.setLayoutParams(new LinearLayout.LayoutParams(
				ViewGroup.LayoutParams.FILL_PARENT,
				ViewGroup.LayoutParams.FILL_PARENT, 1));
		
		TextView textView = (TextView) view.findViewById(R.id.tab_label);
		textView.setText(text);

		mTabViews.add(view);
		
		TabHost.TabSpec tab = mTabHost.newTabSpec(tagId);
		tab.setIndicator(view);
        tab.setContent(intent);
        mTabHost.addTab(tab);
	}
	
	protected void setCurrentTab(final int tabPos) {
		for (int i = 0; i < mTabViews.size(); i++) {
			View v = mTabViews.get(i);
			if (i == tabPos) {
				v.setBackgroundResource(R.drawable.tabbar_bottom_focused);
			} else {
				v.setBackgroundResource(0);
			}
		}
	}
}
